import threading
import client
import tkinter as tk
from UI import *
from HeartGame import HeartGame

class main:
    '''
    可以调用send_message_through_client()和send_message_throuth_server_to_all()向客户端发送消息
    接收到消息之后会自动调用handle_message()函数
    '''

    '''
    与服务器的通信格式：
    msg = {
        "type": "id_txt"/"message"/... 消息类型
        "content": 消息内容    
    }
    '''

    def __init__(self, server_ip='2409:8a30:291:1b01:be24:11ff:fe13:d84e', port=65432):
        self.client_id_txt = "" #服务器文字id（名字）
        self.client_id = None

        # 定义获取新消息事件
        #self.new_msg_from_HeartGame_event = threading.Event()
        # 客户端client
        self.client = client.client(get_message_from_client=self.get_message_from_client, server_ip=server_ip, port=port)

        # 创建游戏界面，但暂时不显示
        self.gameui = HeartGame(send=self.send_message_through_client)

        # 创建主窗口
        self.login_root = tk.Tk()
        self.login_ui = LoginUI(self.login_root, self.send_client_id_txt)
        print(1)
        self.login_root.mainloop()
        print(2)

        self.enter_room_root = tk.Tk()
        self.enter_room_ui = EnterRoomUI(self.enter_room_root, self.send_room_id)
        self.enter_room_root.mainloop()

        #-------------测试用代码--------------
        #self.send_message_through_client({"type": 'id_txt', "content": "1"})
        #self.send_room_id(room_id='1')
        #------------------------------------

        self.play_root = tk.Tk()
        self.gameui.initiation(self.play_root)
        self.gameui.update_display()
        self.play_root.mainloop()

    def get_message_from_client(self, msg):  # 从client获得消息
        print('in get_message_from_client')
        print(msg)
        if msg is not None:
            self.handle_message(msg=msg)

    def send_message_through_client(self, msg):  # 用client向服务器发送消息
        print(msg)
        if not isinstance(msg, dict):
            print('try to send message with wrong format')
            return
        self.client.send_message(msg)

    def handle_room_id_from_UI(self, room_id): # 处理从UI获得输入的房间号，作为UI的callback
        '''将获得的房间号发送给服务器'''
        msg = {"type": "entering room request", "content": room_id}
        self.send_message_through_client(msg=msg)

    def handle_message(self, msg):  # 处理消息
        if msg["type"] == "message": #处理消息类型的消息
            client_id_txt = msg["client_id_txt"]
            print(f'收到来自{client_id_txt}的消息')
            message = msg["msg"]
            self.gameui.display_message(client_id_txt + ": " + message)

        elif msg["type"] == "client_id":
            self.client_id = msg["content"]
            
        elif msg["type"] == "txt_id":
            self.gameui.player_txt_ids = [msg["content"][(i + self.gameui.position + 4) % 4] for i in range(0, 4)]
            print(self.gameui.player_txt_ids)
            self.gameui.update_display()

        elif msg["type"] == "notification": #处理通知类型的消息
            self.handle_notification(notification=msg["content"])

        elif msg["type"] == "other player's card": #处理其他玩家出牌类型的消息
            print('got other player\'s card')
            self.handle_other_player_card(card=msg["content"]["card"], player=msg["content"]["from"])

        elif msg["type"] == "players' positions": #处理当前玩家的座次
            print('got players\' positions')
            print(msg)
            self.handle_players_positions(players_positions=msg["content"])

        elif msg["type"] == "send hand": #处理服务器发来的手牌
            print('got hand')
            self.gameui.hand = msg["content"]
            self.gameui.update_display()
        
        elif msg["type"] == "first player": #设置第一个出牌的玩家
            self.handle_first_player(msg["content"])

        elif msg["type"] == "get score": #处理玩家得分的消息
            print('got score')
            position = msg["content"]["position"]
            score = msg["content"]["score"]
            self.gameui.player_scores[(position - self.gameui.position + 4) % 4] += score
            self.gameui.player_game_scores[(position - self.gameui.position + 4) % 4] += score
            self.gameui.update_display()

        elif msg["type"] == "game end": #处理小局结束
            self.handle_game_end(msg["content"])

    def send_client_id_txt(self): # 向服务器发送文字id
        print('id_txt sent')
        self.get_client_id_txt()
        self.send_message_through_client({"type": 'id_txt', "content": self.client_id_txt})

    def send_room_id(self, room_id):
        msg = {
            "type": "entering room request",
            "content": room_id
        }
        self.send_message_through_client(msg=msg)

    def get_client_id_txt(self): # 从UI获取文字id
        self.client_id_txt = self.login_ui.client_id_txt

    '''def run(self):# 运行主循环
        
        self.root.mainloop()
        # 关闭客户端连接
        self.client.sock.close()'''

    def handle_notification(self, notification): #处理通知（进入房间请求是否通过）
        print('handling notification')
        if notification == "entering room denied":
            print('room not available')
            #tk.messagebox.showinfo("进入房间拒绝", "房间人数已满！")
        elif notification == "entering room allowed":
            print('allowed')
            self.enter_room_root.destroy()

    def handle_other_player_card(self, card, player): #处理其他玩家出的手牌
        #以自己为下方，将其他玩家出的牌放于正确的位置（0为下方）
        if None not in self.gameui.played_cards: #如果所有玩家都已经出过牌，又有玩家出牌，说明新的一轮开始了
            self.gameui.reset_played_cards()
        self.gameui.played_cards[(self.gameui.players_to_position[player] - self.gameui.position + 4) % 4] = card
        print(self.gameui.played_cards)
        self.gameui.next_turn()
        
        self.gameui.update_display()
    
    def handle_players_positions(self, players_positions): #处理玩家座次
        players_positions = {int(key): value for key, value in players_positions.items()}
        self.gameui.players_to_position = players_positions
        self.gameui.position = players_positions[self.client_id]
        print('in handle players positions')
        print(players_positions)

    def handle_first_player(self, first):
        print(f'frist player is {first}')
        self.gameui.first_player = first
        self.gameui.current_turn = self.gameui.first_player
        print('in handle first player')
        if self.gameui.position == first: #自己先出牌
            self.gameui.set_enable(True)
        else:
            self.gameui.set_enable(False)
        self.gameui.update_display()

    def handle_game_end(self, total_scores):
        self.gameui.player_scores = [total_scores[(i + self.gameui.position + 4) % 4] for i in range(0, 4)]
        self.gameui.player_game_scores = [0, 0, 0, 0]
        self.gameui.update_display()
        

if __name__ == "__main__":

    app = main(server_ip='240e:361:1409:ea10:2481:c757:3d62:6')
    app.run()